﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.UI;

namespace ZHDJ.WebPage
{
    /// <summary>
    /// word文档
    /// </summary>
    public class WordBusiness
    {
        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="page">当前页面</param>
        /// <param name="ctrl">导出内容的控件</param>
        /// <param name="fileName">文件名</param>
        public static void Export(Page page,Control ctrl,string fileName)
        {
            System.IO.StringWriter SW = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter HTW = new System.Web.UI.HtmlTextWriter(SW);
            ctrl.RenderControl(HTW);
            Export(page, SW.ToString(), fileName);
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="page">当前页面</param>
        /// <param name="ctrl">导出内容的控件</param>
        /// <param name="fileName">文件名</param>
        public static void Export(Page page, string content, string fileName)
        {
            
            //Page为要导出的对象,当前是Page,如果是DataGrid,DataList等都可以
            page.Response.Buffer = true;
            page.Response.Clear();
            page.Response.ClearContent();
            page.Response.ClearHeaders();
            page.Response.ContentType = "application/ms-word";
            //Response.ContentType是输出流的 HTTP MIME 类型
            //Response.ContentType      --- word文件
            //application/vnd.ms-excel --- excel文件
            //
            page.Response.Charset = "utf-8";
            page.Response.ContentEncoding = System.Text.Encoding.GetEncoding("GBK");
            page.Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
            //attachment --- 作为附件下载
            //inline --- 在线打开
            //filename如过是中文,则可以用HttpUtility.UrlEncode(fileName,System.Text.Encoding.UTF8)
            //进行进行编码,以解决文件名乱码的问题
            page.Response.Write(content);
            page.Response.Flush();
            page.Response.Close();
        }
    }
}
